import logging
from typing import Optional
from fastapi import FastAPI, Request, HTTPException, Depends, Header
from contextlib import asynccontextmanager
from app.core.config import settings
from app.providers.easemate_provider import EaseMateProvider

# --- logging 配置和 logger 定义 ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# --- 全局状态，用于持有唯一的 provider 实例 ---
app_state = {}

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    在应用启动时，创建并初始化一个全局唯一的 Provider 实例。
    """
    logger.info("应用启动...开始初始化持久化浏览器...")
    provider = EaseMateProvider()
    await provider.initialize_browser()
    app_state["provider"] = provider
    logger.info("浏览器初始化完成，应用准备就绪。")
    
    yield
    
    logger.info("应用关闭...正在关闭浏览器...")
    if "provider" in app_state:
        await app_state["provider"].close_browser()
    logger.info("浏览器已关闭。")

# --- FastAPI 应用实例 ---
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description=settings.DESCRIPTION,
    lifespan=lifespan
)

# --- 安全性依赖 ---
async def verify_api_key(authorization: Optional[str] = Header(None)):
    if settings.API_MASTER_KEY and settings.API_MASTER_KEY != "1":
        if not authorization or "bearer" not in authorization.lower():
            raise HTTPException(status_code=401, detail="需要 Bearer Token 认证。")
        
        token = authorization.split(" ")[-1]
        if token != settings.API_MASTER_KEY:
            raise HTTPException(status_code=403, detail="无效的 API Key。")

# --- API 路由 ---
@app.post("/v1/chat/completions", dependencies=[Depends(verify_api_key)])
async def chat_completions(request: Request):
    provider = app_state.get("provider")
    if not provider or not provider.is_ready():
        raise HTTPException(status_code=503, detail="服务正在初始化或尚未就绪，请稍后重试。")
    
    try:
        request_data = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="无效的 JSON 请求体。")

    # --- 关键修正：直接返回 provider 的同步方法的结果，不使用 await ---
    return provider.chat_completion(request_data)

@app.get("/v1/models", dependencies=[Depends(verify_api_key)])
async def list_models():
    # get_models 可以保持原样，因为它是一个简单的异步方法
    provider = app_state.get("provider")
    if not provider:
        raise HTTPException(status_code=503, detail="服务尚未就绪。")
    return await provider.get_models()

@app.get("/", summary="根路径", include_in_schema=False)
def root():
    return {
        "message": f"欢迎来到 {settings.APP_NAME} v{settings.APP_VERSION}",
        "status": "ok",
    }
